package civicinity.ist.psu.edu.profile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import com.facebook.android.Facebook;

import civicinity.ist.psu.edu.CivicinityLogin;
import civicinity.ist.psu.edu.CivicinityMainpage;
import civicinity.ist.psu.edu.R;
import civicinity.ist.psu.edu.facebook.SessionEvents;
import civicinity.ist.psu.edu.facebook.SessionStore;
import civicinity.ist.psu.edu.facebook.SessionEvents.LogoutListener;
import civicinity.ist.psu.edu.rssfeed.RSSFeedService;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceClickListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;

/**
 * Setting class
 * All downloading processes are done in this activity
 * Since the amount of time to download the lists varies depending on the connectivity level.
 * and especially, the user defined lists are pretty huge to download, therefore, the application
 * expects the user to be in the good connectivity area.
 * 1. Downloading Local Lists
 * 2. Downloading User Defined Lists
 * 3. Downloading Floracache Lists
 * 4. Check the version
 * 5. Logout
 * @author kyunghan
 *
 */
public class CivicinityPreferences extends PreferenceActivity {

	private SharedPreferences mPref;
	private String mUsername;
	private boolean[] mSelect;
	private String[] mGroupName;
	static final int UNINSTALL_REQUEST = 0;
	
	private ToggleButton togglebutton;
	
	private Facebook mFacebook;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    mFacebook = new Facebook("263466350349965");
	    
	    addPreferencesFromResource(R.xml.preferences);
	    // TODO Auto-generated method stub
	    
	    // Define Preferences to store username and password
		mPref = PreferenceManager.getDefaultSharedPreferences(this);
		
	    TogglePreferences notificationPref = (TogglePreferences) findPreference("notification");
	    /*
	    notificationPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				// TODO Auto-generated method stub
				toggleHandler();
				return true;
			}
	    	
	    });
	    */
	    
	    Log.i("K", "notification_on : " + mPref.getBoolean("notification_on", true));
	    
		togglebutton = (ToggleButton) findViewById(R.id.toggle_button);
		if(mPref.getBoolean("notification_on", true)) {
			notificationPref.setToggleButtonChecked(true);
		}
		else {
			notificationPref.setToggleButtonChecked(false);
		}
		
	    Preference logoutPref = (Preference) findPreference("userlogout");
	    logoutPref.setTitle("Logout (" + mPref.getString("username", "") + ")");
	    logoutPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference preference) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(CivicinityPreferences.this)
		   		.setTitle("Logout")
		   		.setMessage("Proceed to Logout?")
		   		.setPositiveButton("Logout", new DialogInterface.OnClickListener() {
		   			public void onClick(DialogInterface dialog, int whichButton) {
		   				
		   				if(mPref.getBoolean("facebook", false)) {
		   					try {
		   						// clear session
		   						SessionStore.clear(CivicinityPreferences.this);
		   						// logout
								mFacebook.logout(CivicinityPreferences.this);
								// update the sharedpreferences values
								SharedPreferences.Editor editor = mPref.edit();
								editor.putBoolean("loggedin", false);
					    		editor.putBoolean("guest_mode", false);
					    		editor.putBoolean("first_time", true);
					    		editor.putBoolean("facebook", false);
					    		editor.commit();
					    		
					    		// go back to the login page
					    		Intent intent = new Intent(CivicinityPreferences.this, CivicinityLogin.class);
						        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_CLEAR_TOP);
								startActivity(intent);
								
								stopService(new Intent(CivicinityPreferences.this, RSSFeedService.class));

					    		CivicinityPreferences.this.finish();
								
								
								
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
		   				}
		   				else {
		   					// update sharedpreferences values.
			   				SharedPreferences.Editor editor = mPref.edit();
							editor.putBoolean("loggedin", false);
				    		editor.putBoolean("guest_mode", false);
				    		editor.putBoolean("first_time", true);
				    		editor.commit();
				    		
				    		Intent intent = new Intent(CivicinityPreferences.this, CivicinityLogin.class);
					        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);
							
							stopService(new Intent(CivicinityPreferences.this, RSSFeedService.class));

				    		finish();
		   				}
		   			}
		   		})
		   		.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		   			public void onClick(DialogInterface dialog, int whichButton) {
		   			}
		   		})
		   		.show();
				return true;
			}
	    });

	    //Preference updatePref = (Preference) findPreference("update");
	    ImageViewPreference imagePref = (ImageViewPreference) findPreference("key1");
	    Resources res = getResources();
	    if(mPref.getBoolean("needUpdate", false)) {
		    Drawable icon = res.getDrawable(R.drawable.icon);
		    imagePref.setComponent(icon, "need upgrade");
	    }
	    else {
	    	Drawable icon = res.getDrawable(R.drawable.icon);
		    imagePref.setComponent(icon, "Recent version is installed");
	    }
	    
	    imagePref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

			@Override
			public boolean onPreferenceClick(Preference arg0) {
				// TODO Auto-generated method stub
				if(mPref.getBoolean("needUpdate", false)) {
					/*
					new AlertDialog.Builder(HelperSettings.this)
					.setTitle(getString(R.string.Upgrade_app_text))
					.setMessage(getString(R.string.Move_to_the_market_Text))
					.setPositiveButton(getString(R.string.Button_yes), new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							Intent intent = new Intent(Intent.ACTION_VIEW);
							intent.setData(Uri.parse("market://details?id=edu.ucla.cens.budburstmobile"));
							startActivity(intent);
						}
					})
					.setNegativeButton(getString(R.string.Button_back), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
						}
					})
					.show();
					*/
				}
				else {
					Toast.makeText(CivicinityPreferences.this, "No need to upgrade", Toast.LENGTH_SHORT).show();
				}
				return false;
			}
	    });
	}
	
	public class SampleLogoutListener implements LogoutListener {
        public void onLogoutBegin() {
            //mText.setText("Logging out...");
        	Log.i("K", "Start logging out...");
        }

        public void onLogoutFinish() {
        	
        	Log.i("K", "Logging out finished...");
			// update sharedpreferences values.
			
        }
    }
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == event.KEYCODE_BACK) {
			
			startActivity(new Intent(this, CivicinityMainpage.class));
			finish();
			
			return true;
		}
		return false;
	}	
}

